<?php

class Validate {
	protected function checkRegExp($regExp, $string) {
		return preg_match($regExp, $string) ? true : false;
		// Kan returnera 0,1,2,3,4 osv ändra! Kolla typen.
	}
	
	public function validateImageUpload() {
		//Code from http://www.bitrepository.com/how-to-validate-an-image-upload.html

		if (!empty($_FILES)) {
			
			include 'config.php';

			$file = $_FILES[FileUploadView::FILE];

			$file_name = $file['name'];

			$error = '';
			// empty

			//Get fileextensions if there is any
			$ext = strtolower(substr(strrchr($file_name, "."), 1));
			
			if ($validation_type == 1) {
				$file_info = getimagesize($_FILES['file']['tmp_name']);

				if (empty($file_info)) {//Not an image?
					$error .= "<p>Den uppladdade filen är ingen bild</p>";
				} else {// an image?
					$file_mime = $file_info['mime'];

					if ($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2') {
						$extension = $ext;
					} else {
						$extension = ($mime[$file_mime] == 'jpeg' ? 'jpg' : $mime[$file_mime]);
					}
					if (!$extension) {
						$extension = '';
						$uploadedImgName = str_replace('.', '', $file_name);
					}
					return true;
				}
			}
		} elseif ($validation_type == 2) {
			if (!in_array($ext, $image_extensions_allowed)) {
				$exts = implode(',', $image_extensions_allowed);
				$error .= "you must upload a file with one of the following extensions: " . $exts;
			}
			$extensions = $ext;
			if ($error == "") {
				$new_file_name = strtolower($file_name);
				$new_file_name = str_replace(' ', '-', $new_file_name);
				$new_file_name = substr($new_file_name, 0, -strlen($ext));
				$new_file_name .= $extension;

				return true;
				//$new_file_name;
			}
		}
		return false;
	}
	
	//firstname and lastname
	public function nameString($string) {
		$regExp = "/^[a-zåäöÅÄÖ]{2,}([\- ]{1}[a-zåäöÅÄÖ]{2,})?$/i";

		if ($this -> checkRegExp($regExp, $string)) {
			return $string;
		} else {
			return false;
		}
	}

	public function userName($string) {
		$regExp = "/^[a-zåäöÅÄÖ]{1}[a-zåäöÅÄÖ\d_]{1,28}$/i";

		if ($this -> checkRegExp($regExp, $string)) {
			return $string;
		} else {
			return false;
		}
	}

	public function email($string) {
		// Regexp snott från internet...
		$regExp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,6}$/";

		if ($this -> checkRegExp($regExp, $string)) {
			return $string;
		} else {
			return false;
		}
	}

	public function Ssn($string) {
		// Skrivit regexp själv
		$regExp = "/^(18|19|20)?[0-9]{2}[0-1][0-9][0-3][0-9](-|\+)?[0-9]{4}$/";

		if ($this -> checkRegExp($regExp, $string)) {
			// Fix standard-format on ssn
			// $this->luhn($string)
			$string = preg_replace("(-|\+)", "", $string);
			// Remove the dash
			$string = substr($string, -10);
			// Remove the beginning 19 if exists

			if ($this -> luhn($string)) {
				return $string;
			}
		}
		return false;
		//Två felmeddelanden. Ett för om det inte stämde för regexp och ett för att det inte stämde med luhn
	}

	// Luhn-check, from wikipedia
	protected function luhn($ssn) {
		$sum = 0;

		for ($i = 0; $i < strlen($ssn) - 1; $i++) {
			$tmp = substr($ssn, $i, 1) * (2 - ($i & 1));
			//växla mellan 212121212
			if ($tmp > 9)
				$tmp -= 9;
			$sum += $tmp;
		}

		//extrahera en-talet
		$sum = (10 - ($sum % 10)) % 10;

		return substr($ssn, -1, 1) == $sum;
	}

	public function date($string) {
		// Skrivit regexp själv
		$regExp = "/^([0-9]{2})?[0-9]{2}((-[0-1][0-9]-)|[0-1][0-9])[0-3][0-9]$/";

		if ($this -> checkRegExp($regExp, $string)) {

			// return a standard format YY-MM-DD

			// Remove the dashes
			$string = preg_replace("(-)", "", $string);

			// Trim the year
			$string = substr($string, -6);

			$year = substr($string, 0, 2);
			$month = substr($string, 2, 2);
			$day = substr($string, 4, 2);

			return $year . "-" . $month . "-" . $day;
		}

		return false;

	}

	public function removeAllTags($string) {
		return strip_tags($string);
	}

	public function removeSomeTags($string, $allowedTags) {
		return strip_tags($string, $allowedTags);
	}

	public function checkPassword($string) {

		if (md5($string) == $this -> fakeDbPassword) {
			return true;
		}

		return false;

	}

	public function checkPasswordFormat($string) {
		// Only validates a-zA-Z0-9_, must have minimum of 6 and at least a CAPITAL, small and digit.
		$regExp = "#.*^(?=(\w){6,})(?=.*[a-z])(?=.*[\d])(?=.*[A-Z])#";
		if ($this -> checkRegExp($regExp, $string)) {
			return $string;
		}
		
		return false;
	}

	public function TestMemberHandler() {
		// Testar korrekta emailadresser
		$correctEmails = array("daniel@domain.se", "daniel.toll@lnu.se", "daniel@student.lnu.se", "ds@s.se", "daniel@student.museum");

		foreach ($correctEmails as $correctEmail) {
			if ($this -> email($correctEmail) == false) {
				echo "correctEmail är felaktig.";
				return false;
			}
		}

		// testar felaktiga mailadresser
		$incorrectEmails = array("daniel@domain", "daniel", "@domain.se", "4ever@hotmail.com"     // Får inte börja på en siffra
		);

		foreach ($incorrectEmails as $incorrectEmail) {
			if ($this -> email($incorrectEmail) !== false) {
				echo "incorrectEmail är felaktig.";
				return false;
			}
		}

		//formValidator
		$correctFormArrays = array(  array("Elin", "Örjansson",  "Elin__1", "hej123Kolikok_", "hej123Kolikok_", "elin@elin.se", "19900307-6602"),
	
		array("maj-li", "Clarelius",  "majs4n", "majs4anärBäsT", "majs4anärBäsT", "majli@majli.nu", "200110150141"));

		foreach ($correctFormArrays as $correctForm) {
			if (!$this->formValidator($correctForm[0], 
			$correctForm[1], 
			$correctForm[2], 
			$correctForm[3], 
			$correctForm[4], 
			$correctForm[5], 
			$correctForm[6])) {
				echo "correctformArray är felaktig.";
				return false;
			}
		}

		$incorrectFormArrays = array( array("123Elin", "Örj!q#nsson", "__Elin__1", "0", "0", "elin@elin", "0307-6602"), 
		array(")=()=()", ".Wilhelmsson Hansson", "", "", "#####Åkebuse_nu", "123Åke.W.H@w.h.se", "600827-327512"), 
		array("mAJ_LI", "Clarelius123",  "daswewwq", "ADASD(%¤()%=#)=eklLK", "hej", "@majli.nu", "1890-07-100120"));

		foreach ($incorrectFormArrays as $incorrectForm) {
			if ($this -> formValidator($incorrectForm[0],  
			$incorrectForm[1], 
			$incorrectForm[2], 
			$incorrectForm[3], 
			$incorrectForm[4], 
			$incorrectForm[5], 
			$incorrectForm[6])) {
				echo "incorrectformArray är felaktig.";
				return false;
			}
		}

		$correctNames = array("Elin", "kalle", "Örjan", "Thomas-Åke", "Nilsson Örjansson", "Ulla-stina");
		foreach ($correctNames as $correctNameString) {
			if (!$this -> nameString($correctNameString)) {
				echo "correctNames är felaktig.";
				return false;
			}
		}

		$incorrectNames = array("123", "Elin123", "#¤=", "<em>Elin</em>", "test123test");
		foreach ($incorrectNames as $incorrectNameString) {
			if ($this -> nameString($incorrectNameString)) {
				echo "incorrectNames är felaktig.";
				return false;
			}
		}

		$correctUserNames = array("Elin2__123", "Elin123", "Örjan123kool", "åke_999", "Britta__", "k00lK4tt");
		foreach ($correctUserNames as $correctUserName) {
			if (!$this -> userName($correctUserName)) {
				echo "correctUserName är felaktig.";
			}
		}

		$incorrectUserNames = array("Super!¤%.&&man", "_Elin", "Roger-åke", "()=//&#¤", "123", "123Hejhopp");
		foreach ($incorrectUserNames as $incorrectUserName) {
			if ($this -> userName($incorrectUserName)) {
				echo "incorrectUserNames är felaktig.";
			}

		}

		$correctSSNs = array("8311118213", "831111-8213", "19831111-8213", "198311118213", "20011111-7206", "831111+8213");

		foreach ($correctSSNs as $correctSSN) {
			if ($this -> ssn($correctSSN) == false) {
				echo "correctSSN är felaktig.";
				return false;
			}
		}

		$incorrectSSNs = array("831111", // To few numbers
			"19831111", // To few numbers
			"198311-118213", // Dash in the wrong place
			"8311118214", // Incorrect luhn
			"22221219-8225", // Incorrect year
			"8323238225", // Incorrect month
			"abs"              // No numbers
		//"831111+8213"       // No dash but + instead
		);

		foreach ($incorrectSSNs as $incorrectSSN) {
			if ($this -> ssn($incorrectSSN) !== false) {
				echo "incorrectSSN är felaktig.";
				return false;
			}
		}

		$correctDates = array("1999-10-01", "99-10-01", "991001", "2000-01-01");

		foreach ($correctDates as $correctDates) {
			if ($this -> date($correctDates) == false) {
				echo "correctDates är felaktig.";
				return false;
			}
		}
		$incorrectDates = array("1999100", // One digit to many
			"99110", // One digit to few
			"99-1001", // Inconsistent dash
			"00-31-01"      // Month that doesn't exist
		);

		foreach ($incorrectDates as $incorrectDates) {
			if ($this -> date($incorrectDates) !== false) {
				echo "incorrectDates är felaktig.";
				return false;
			}
		}

		// Filter string output. Usefull to prevent user from adding style-elements to our site.

		$inputTextString = "<script> alert('testar') ; </script> <b>Lorem</b> ipsum dolor sit amet, consectetur adipiscing elit.<br /> Cras rutrum tincidunt velit sit amet porta. <h1>Vivamus convallis ullamcorper sem nec volutpat.</h1> Aenean eu tellus sed turpis pellentesque imperdiet. Aliquam erat volutpat. Morbi tempor porttitor eros, vitae bibendum lacus bibendum convallis. <a href='www.google.com' alt='testar'>Phasellus</a> mi nibh, pellentesque ut euismod vitae, vulputate eget velit. Proin massa nibh, suscipit vel tincidunt eget, elementum at tortor. <div id='testar'>Sed sollicitudin sodales diam vitae aliquet.</div> <marquee>Phasellus egestas convallis facilisis.</marquee> Praesent ornare, mi vitae mattis laoreet, nulla velit placerat diam, nec vulputate massa nisi vitae odio. <p>Nunc lectus neque, feugiat eu lacinia vitae, dapibus vitae nisl.</p> Cras mi nulla, bibendum a sodales sit amet, pulvinar vitae nunc.";

		$expectedOutputTextString = " alert('testar') ; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras rutrum tincidunt velit sit amet porta. Vivamus convallis ullamcorper sem nec volutpat. Aenean eu tellus sed turpis pellentesque imperdiet. Aliquam erat volutpat. Morbi tempor porttitor eros, vitae bibendum lacus bibendum convallis. Phasellus mi nibh, pellentesque ut euismod vitae, vulputate eget velit. Proin massa nibh, suscipit vel tincidunt eget, elementum at tortor. Sed sollicitudin sodales diam vitae aliquet. Phasellus egestas convallis facilisis. Praesent ornare, mi vitae mattis laoreet, nulla velit placerat diam, nec vulputate massa nisi vitae odio. Nunc lectus neque, feugiat eu lacinia vitae, dapibus vitae nisl. Cras mi nulla, bibendum a sodales sit amet, pulvinar vitae nunc.";

		if (strlen($expectedOutputTextString) - similar_text($expectedOutputTextString, $this -> removeAllTags($inputTextString)) !== 0) {
			echo "removeAllTags failed to do so!<br />";

			echo "<p>$expectedOutputTextString</p>";
			echo "<p>" . $this -> removeAllTags($inputTextString) . "</p>";

			echo "Char that don't match: " . (strlen($expectedOutputTextString) - similar_text($expectedOutputTextString, $this -> removeAllTags($inputTextString)));
			return false;
		}

		$expectedOutputTextString = " alert('testar') ; <b>Lorem</b> ipsum dolor sit amet, consectetur adipiscing elit. Cras rutrum tincidunt velit sit amet porta. Vivamus convallis ullamcorper sem nec volutpat. Aenean eu tellus sed turpis pellentesque imperdiet. Aliquam erat volutpat. Morbi tempor porttitor eros, vitae bibendum lacus bibendum convallis. <a href='www.google.com' alt='testar'>Phasellus</a> mi nibh, pellentesque ut euismod vitae, vulputate eget velit. Proin massa nibh, suscipit vel tincidunt eget, elementum at tortor. Sed sollicitudin sodales diam vitae aliquet. Phasellus egestas convallis facilisis. Praesent ornare, mi vitae mattis laoreet, nulla velit placerat diam, nec vulputate massa nisi vitae odio. Nunc lectus neque, feugiat eu lacinia vitae, dapibus vitae nisl. Cras mi nulla, bibendum a sodales sit amet, pulvinar vitae nunc.";

		$allowedTags = "<b><a>";

		if (strlen($expectedOutputTextString) - similar_text($expectedOutputTextString, $this -> removeSomeTags($inputTextString, $allowedTags)) !== 0) {
			echo "removeAllTags failed to do so!<br />";

			echo "<p>$expectedOutputTextString</p>";
			echo "<p>" . $this -> removeSomeTags($inputTextString, $allowedTags) . "</p>";

			echo "Char that don't match: " . (strlen($expectedOutputTextString) - similar_text($expectedOutputTextString, $this -> removeSomeTags($inputTextString, $allowedTags)));
			return false;
		}

		// Lets do the password-check
		// echo md5("password") ; // = 5f4dcc3b5aa765d61d8327deb882cf99

		$password = "password";

		if ($this -> checkPassword($password) == false) {
			echo "Password check failed when trying correct password.";
			return false;
		}

		$wrongPassword = "noPassword";

		if ($this -> checkPassword($wrongPassword) !== false) {
			echo "Password check failed when trying wrong password.";
			return false;
		}

		$correctNumbers = array(15, 0, -165, 4.4, "12");

		foreach ($correctNumbers as $correctNumber) {
			if ($this -> checkNumber($correctNumber) === false) {
				echo "CheckNumber failed when trying correct number ($correctNumber).";
				return false;
			}
		}

		$incorrectNumbers = array("b4", // a string
			NULL, // Not to be mixed with 0
			"four"      // Number in writings
		);

		foreach ($incorrectNumbers as $incorrectNumber) {
			if ($this -> checkNumber($incorrectNumber) !== false) {
				echo "CheckNumber failed when trying incorrect number ($incorrectNumber).";
				return false;
			}
		}

		// Check if the checkNumbers can handle strings

		$correctNumbers = array("noll", "ett", 1);

		foreach ($correctNumbers as $correctNumber) {
			if ($this -> checkNumber($correctNumber, "like") === false) {
				echo "CheckNumber failed when trying correct number ($correctNumber).";
				return false;
			}
		}

		$incorrectNumbers = array("b4", // a string
			NULL, // Not to be mixed with 0
			"twelve"      // Number in writings that don't exists
		);

		foreach ($incorrectNumbers as $incorrectNumber) {
			if ($this -> checkNumber($incorrectNumber) !== false) {
				echo "CheckNumber failed when trying correct number ($incorrectNumber).";
				return false;
			}
		}

		$correctPasswordFormats = array("Password123", "123Password", "Pass123pass");

		foreach ($correctPasswordFormats as $correctPasswordFormat) {
			if ($this -> checkPasswordFormat($correctPasswordFormat) == false) {
				echo "CheckPasswordFormad failed when trying $correctPasswordFormat";
				return false;
			}

		}

		$incorrectPasswordFormats = array("password123", // No capital letter
			"Password", // No digits
			"PASS123", // No gemena
			"Pas2", // To short
			"p@ss123A", // Strange sign
			"123456", // Only digits
			"@@@@//\\//..."     // Only weird stuff

		);

		foreach ($incorrectPasswordFormats as $incorrectPasswordFormat) {
			if ($this -> checkPasswordFormat($incorrectPasswordFormat) !== false) {
				echo "CheckPasswordFormad failed when trying $incorrectPasswordFormat";
				return false;
			}

		}
		return true;

	}
}

